<?php
/**
 * Created by PhpStorm.
 * User: yuyiwen
 * Date: 2018/11/2
 * Time: 上午9:22
 */

namespace app\index\model;


class Member
{
    /**
     * 获取一级伙伴
     */
    public function getPartners ($id)
    {
        return db('member')
            ->field('a.*,b.nickname pnickname')
            ->alias('a')
            ->join('member b' , 'a.pid = b.id' , 'left')
            ->where('a.pid' , $id)
//            ->buildsql();
            ->select();
    }

    /**
     * 获取 一级、二级、三级伙伴
     * @param $id   当前会员的id
     */
    public function getAllPartners ($id)
    {
        $return = [];
        $level1 = $this->getPartners($id);

        if(!empty($level1)){
            $return['level1'] = $level1;
            // 循环一级会员，拿到二级会员
            foreach ($level1 as $k1 => $v1) {
                $tmp_level2[] = $this->getPartners($v1['id']);
            }

            // 重组二级会员数组
            foreach ($tmp_level2 as $k2 => $v2) {
                foreach ($v2 as $v3) {
                    $level2[] = $v3;
                }
            }

            if (!empty($level2)) {
                $return['level2'] = $level2;
                // 循环二级会员，拿到三级会员
                foreach ($level2 as $k1 => $v1)
                {
                    $tmp_level3[] =  $this->getPartners($v1['id']);
                }

                // 重组三级会员数组
                foreach ($tmp_level3 as $k2 => $v2)
                {
                    foreach ($v2 as $v3)
                    {
                        $level3[] = $v3;
                    }
                }
                if (!empty($level3)) {
                    $return['level3'] = $level3;
                }

            }


        }
        return $return;

    }

    /**
     * 获取上级
     */
    public function getReferee ($id)
    {
        // 获取会员的数据
        $info = db('member')->find($id);
        $referee = db('member')->where('id' , $info['pid'])->find();
        return $referee;
    }
}